<template>
  <div ref="parentRef" class="watermark-container">
    <slot></slot>
  </div>
</template>

<script setup>
import { watchEffect, ref, onMounted, onUnmounted } from "vue";
import useWatermarkBg from "./useWatermarkBg";
const props = defineProps({
  text: {
    type: String,
    required: true,
    default: "watermark",
  },
  fontSize: {
    type: Number,
    default: 40,
  },
  gap: {
    type: Number,
    default: 20,
  },
});
const bg = useWatermarkBg(props);
console.log(bg.value);
const parentRef = ref(null);
let div;
const flag = ref(0)
watchEffect(() => {
  flag.value
  if (!parentRef.value) {
    return;
  }
  if (div) {
    div.remove();
  }
  const { base64, styleSize } = bg.value;
  div = document.createElement("div");
  div.style.backgroundImage = `url(${base64})`;
  div.style.backgroundSize = `${styleSize}px ${styleSize}px`;
  div.style.backgroundRepeat = "repeat";
  div.style.width = "100%";
  div.style.height = "100%";
  div.style.zIndex = 9999;
  div.style.position = "absolute";
  div.style.inset = 0;
  parentRef.value.appendChild(div);
});

// 防篡改
let ob = null;
onMounted(() => {
  ob = new MutationObserver((records) => {
    for (const record of records) {
      // 删除水印
      for (const node of record.removedNodes) {
        if(node===div){
          flag.value++
          return
        }
      }
      // 修改
      if(record.target===div){
        flag.value++
        return
      }
    }
  });
  ob.observe(parentRef.value, {
    childList: true,
    subtree: true,
    attributes: true,
  });
});
onUnmounted(() => {
  ob && ob.disconnect();
  div=null
});
</script>

<style lang="scss" scoped>
.watermark-container {
  position: relative;
}
</style>
